package com.amoyt.project.security.handler;


import com.amoyt.project.constants.ResponseConstants;
import com.amoyt.project.domain.res.Result;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Desc 认证失败处理器 (也即未登录)
 */
@Component
@Slf4j
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException, JsonProcessingException {
        //处理异常
//        Result result = Result.error().message("用户认证失败，请重新登录").code(HttpStatus.UNAUTHORIZED.value());
//        String str = JSON.toJSONString(result);
//        response.setStatus(200);
//        response.setContentType("application/json");
//        response.setCharacterEncoding("utf-8");
//        response.getWriter().print(str);
        log.error("用户认证失败!");
        Result result = Result.error(ResponseConstants.AUTHENTICATION_FAILED);
        ObjectMapper objectMapper = new ObjectMapper();
        String returnStr = objectMapper.writeValueAsString(result);
        response.setStatus(200);
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        response.getWriter().print(returnStr);
    }
}